package com.yunchang.springboot.scheduled.MWS;

import com.amazonservices.mws.client.MwsUtl;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersAsync;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersAsyncClient;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersException;
import com.amazonservices.mws.orders._2013_09_01.model.*;
import com.yunchang.springboot.config.MWS.MarketplaceWebServiceOrdersConfig;
import com.yunchang.springboot.mapper.mws.orders.*;
import com.yunchang.springboot.mapper.shop.AreaMapper;
import com.yunchang.springboot.mapper.shop.ShopAreaMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.models.Area;
import com.yunchang.springboot.models.DO.mws.orders.*;
import com.yunchang.springboot.models.Shop;
import com.yunchang.springboot.utils.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MwsOrderSchedule {
    @Resource
    ShopMapper shopMapper;
    @Resource
    ShopAreaMapper shopAreaMapper;
    @Resource
    MwsOrdersMapper mwsOrdersMapper;
    @Resource
    MwsOrdersBuyerTaxInfoMapper mwsOrdersBuyerTaxInfoMapper;
    @Resource
    MwsOrdersPaymentExecutionDetailMapper mwsOrdersPaymentExecutionDetailMapper;
    @Resource
    MwsOrdersPaymentMethodDetailsMapper mwsOrdersPaymentMethodDetailsMapper;
    @Resource
    MwsOrdersTaxRegistrationDetailsMapper mwsOrdersTaxRegistrationDetailsMapper;
    @Resource
    MwsOrderItemsMapper mwsOrderItemsMapper;
    @Resource
    MwsOrderItemsPromotionIdsMapper mwsOrderItemsPromotionIdsMapper;

    /**
     * 错误重试次数
     */
    private static final Integer MAX_ERROR_NUM = 3;

    @Transactional(rollbackFor = Exception.class)
    public void GetListOrdersAsync() {
        // Get a client connection.
        //获得当前日期时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //减去8小时到格林尼治时间
        LocalDateTime nowDateTime = LocalDateTime.now().minusHours(8);
        int nowYear = nowDateTime.getYear();
        int nowMonth = nowDateTime.getMonthValue();
        int nowDay = nowDateTime.getDayOfMonth();
        int nowHour = nowDateTime.getHour();
        nowDateTime = LocalDateTime.of(nowYear, nowMonth, nowDay, nowHour, 0, 0);
        LocalDateTime preDateTime = nowDateTime.minusHours(1);
        int preYear = preDateTime.getYear();
        int preMonth = preDateTime.getMonthValue();
        int preDay = preDateTime.getDayOfMonth();
        int preHour = preDateTime.getHour();
        List<Shop> shopList = shopMapper.getAllList();
        //直接根据店铺、区域来生成client
        for (Shop shop : shopList) {
            String awsAccessKeyId = CryptoUtil.decode(shop.getAwsAccessKeyId());
            String secretKey = CryptoUtil.decode(shop.getSecretKey());
            String brandName = shop.getBrandName();
            String sellerId = CryptoUtil.decode(shop.getSellerId());
            String mwsAuthToken = CryptoUtil.decode(shop.getMwsAuthToken());
            //获得这个店铺对应的area信息
            List<Area> areaList = shopAreaMapper.getAreaListByShopId(shop.getId());
            AREA:
            for (Area area : areaList) {
                if (area.getMwsCountryCode().equals("EU")) {
                    continue AREA;
                }
                String serviceURL = area.getMwsEndPoint();
                MarketplaceWebServiceOrdersAsyncClient client = MarketplaceWebServiceOrdersConfig.getAsyncClient(awsAccessKeyId, secretKey, serviceURL);
                List<ListOrdersRequest> requestList = new ArrayList<ListOrdersRequest>();
                ListOrdersRequest request = new ListOrdersRequest();
                request.setSellerId(sellerId);
                request.setMWSAuthToken(mwsAuthToken);
                XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
                lastUpdatedAfter.setYear(preYear);
                lastUpdatedAfter.setMonth(preMonth);
                lastUpdatedAfter.setDay(preDay);
                lastUpdatedAfter.setTime(preHour, 0, 0);
                request.setLastUpdatedAfter(lastUpdatedAfter);
                XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
                lastUpdatedBefore.setYear(nowYear);
                lastUpdatedBefore.setMonth(nowMonth);
                lastUpdatedBefore.setDay(nowDay);
                lastUpdatedBefore.setTime(nowHour, 0, 0);
                request.setLastUpdatedBefore(lastUpdatedBefore);
                List<String> orderStatus = new ArrayList<String>();
                request.setOrderStatus(orderStatus);
                List<String> marketplaceId = new ArrayList<String>();
                marketplaceId.add(area.getMarketplaceId());
                request.setMarketplaceId(marketplaceId);
                List<String> fulfillmentChannel = new ArrayList<String>();
                request.setFulfillmentChannel(fulfillmentChannel);
                List<String> paymentMethod = new ArrayList<String>();
                request.setPaymentMethod(paymentMethod);
                Integer maxResultsPerPage = 100;
                request.setMaxResultsPerPage(maxResultsPerPage);
                System.out.println("------------------------获取订单数据开始-------------------------------");
                System.out.println("shopName:" + shop.getBrandName());
                System.out.println("MWSAuthToken:" + request.getMWSAuthToken());
                System.out.println("sellerId:" + sellerId);
                System.out.println("area:" + area.getMwsCountryCode());
                System.out.println("AwsAccessKeyId:" + awsAccessKeyId);
                System.out.println("secretKey:" + secretKey);
                requestList.add(request);
                System.out.println("开始启动线程");
                List<Order> orderList = invokeListOrders(client, requestList);
                System.out.println("------------------------获取订单数据结束-------------------------------");
                System.out.println("------------------------获取订单明细数据开始-------------------------------");
                List<ListOrderItemsRequest> listOrderItemsRequests = new ArrayList<ListOrderItemsRequest>();
                for (Order order : orderList) {
                    String amazonOrderId = order.getAmazonOrderId();
                    ListOrderItemsRequest listOrderItemsRequest = new ListOrderItemsRequest();
                    listOrderItemsRequest.setAmazonOrderId(amazonOrderId);
                    listOrderItemsRequest.setSellerId(sellerId);
                    listOrderItemsRequest.setMWSAuthToken(mwsAuthToken);
                    listOrderItemsRequests.add(listOrderItemsRequest);
                }
                HashMap<String, List<OrderItem>> listOrderItems = invokeListOrderItems(client, listOrderItemsRequests);
                System.out.println("订单明细数量:" + listOrderItems.size());
                System.out.println("------------------------获取订单明细数据结束-------------------------------");
                log.info("开始想数据库录入数据");
                //订单部分
                HashMap<String, List> orderResultMap = packageOrderData(orderList, brandName, shop.getSellerId(), area.getMwsCountryCode());
                if (null != orderResultMap.get("mwsOrdersList") && orderResultMap.get("mwsOrdersList").size() != 0) {
                    List<MwsOrders> mwsOrdersList = orderResultMap.get("mwsOrdersList");
                    mwsOrdersMapper.insertList(mwsOrdersList);
                }
                if (null != orderResultMap.get("mwsOrdersBuyerTaxInfoList") && orderResultMap.get("mwsOrdersBuyerTaxInfoList").size() != 0) {
                    List<MwsOrdersBuyerTaxInfo> mwsOrdersBuyerTaxInfoList = orderResultMap.get("mwsOrdersBuyerTaxInfoList");
                    mwsOrdersBuyerTaxInfoMapper.insertList(mwsOrdersBuyerTaxInfoList);
                }
                if (null != orderResultMap.get("mwsOrdersPaymentExecutionDetailList") && orderResultMap.get("mwsOrdersPaymentExecutionDetailList").size() != 0) {
                    List<MwsOrdersPaymentExecutionDetail> mwsOrdersPaymentExecutionDetailList = orderResultMap.get("mwsOrdersPaymentExecutionDetailList");
                    mwsOrdersPaymentExecutionDetailMapper.insertList(mwsOrdersPaymentExecutionDetailList);
                }
                if (null != orderResultMap.get("mwsOrdersPaymentMethodDetailsList") && orderResultMap.get("mwsOrdersPaymentMethodDetailsList").size() != 0) {
                    List<MwsOrdersPaymentMethodDetails> mwsOrdersPaymentMethodDetailsList = orderResultMap.get("mwsOrdersPaymentMethodDetailsList");
                    mwsOrdersPaymentMethodDetailsMapper.insertList(mwsOrdersPaymentMethodDetailsList);
                }
                if (null != orderResultMap.get("mwsOrdersTaxRegistrationDetailsList") && orderResultMap.get("mwsOrdersTaxRegistrationDetailsList").size() != 0) {
                    List<MwsOrdersTaxRegistrationDetails> mwsOrdersTaxRegistrationDetailsList = orderResultMap.get("mwsOrdersTaxRegistrationDetailsList");
                    mwsOrdersTaxRegistrationDetailsMapper.insertList(mwsOrdersTaxRegistrationDetailsList);
                }
                log.info("订单数据添加成功");
                //订单明细部分
                HashMap<String, List> orderItemResultMap = packageOrderItemData(listOrderItems);
                if (null != orderItemResultMap.get("mwsOrderItemsList") && orderItemResultMap.get("mwsOrderItemsList").size() != 0) {
                    List<MwsOrderItems> mwsOrderItemsList = orderItemResultMap.get("mwsOrderItemsList");
                    mwsOrderItemsMapper.insertList(mwsOrderItemsList);
                }
                if (null != orderItemResultMap.get("mwsOrderItemsPromotionIdsList") && orderItemResultMap.get("mwsOrderItemsPromotionIdsList").size() != 0) {
                    List<MwsOrderItemsPromotionIds> mwsOrderItemsPromotionIdsList = orderItemResultMap.get("mwsOrderItemsPromotionIdsList");
                    mwsOrderItemsPromotionIdsMapper.insertList(mwsOrderItemsPromotionIdsList);
                }
                log.info("订单明细数据添加成功");
            }
        }
    }

    /**
     * 获取所有订单数据的方法
     * <p>
     * 通过这个方法去获得订单和对应明细的所有数据
     */
    public static List<Order> invokeListOrders(MarketplaceWebServiceOrdersAsync client, List<ListOrdersRequest> requestList) {
        // Call the service async.
        log.info("开始获取订单");
        List<Order> newOrderList = new ArrayList<>();
        for (ListOrdersRequest request : requestList) {
            String sellerId = request.getSellerId();
            String mwsAuthToken = request.getMWSAuthToken();

            NUM:
            for (int i = 0; i < MAX_ERROR_NUM; i++) {
                try {
                    Future<ListOrdersResponse> future = client.listOrdersAsync(request);
                    ListOrdersResponse response = future.get();
                    ListOrdersResult listOrdersResult = response.getListOrdersResult();
                    newOrderList.addAll(listOrdersResult.getOrders());
                    //获取nextToken值
                    String nextToken = listOrdersResult.getNextToken();
                    //使用递归来获取下一页数据
                    if (nextToken != null) {
                        newOrderList = getOrderListByNextToken(newOrderList, client, sellerId, mwsAuthToken, nextToken);
                    }
                    System.out.println("orderSize:" + newOrderList.size());
                    log.info("获取订单结束");
                    break NUM;
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof MarketplaceWebServiceOrdersException) {
                        // Exception properties are important for diagnostics.
                        MarketplaceWebServiceOrdersException ex =
                                (MarketplaceWebServiceOrdersException) cause;
                        ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
                        System.out.println("当前线程：" + Thread.currentThread().getName());
                        System.out.println("Service Exception:");
                        System.out.println("RequestId: " + rhmd.getRequestId());
                        System.out.println("Timestamp: " + rhmd.getTimestamp());
                        System.out.println("Message: " + ex.getMessage());
                        System.out.println("StatusCode: " + ex.getStatusCode());
                        System.out.println("ErrorCode: " + ex.getErrorCode());
                        System.out.println("ErrorType: " + ex.getErrorType());
                        try {
                            if (ex.getStatusCode() == 503) {
                                System.out.println("睡眠1分钟");
                                Thread.sleep(61000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return newOrderList;
    }


    /**
     * 获取下一页订单的实现方法
     */
    private static List<Object> invokeListOrdersByNextToken(MarketplaceWebServiceOrdersAsync client, List<ListOrdersByNextTokenRequest> requestList) {
        // Call the service async.
        log.info("获取下一页订单开始");
        List<Object> responseList = new ArrayList<Object>();
        for (ListOrdersByNextTokenRequest request : requestList) {
            NUM:
            for (int i = 0; i < MAX_ERROR_NUM; i++) {

                Object xresponse;
                try {
                    Future<ListOrdersByNextTokenResponse> future = client.listOrdersByNextTokenAsync(request);
                    ListOrdersByNextTokenResponse response = future.get();
                    ResponseHeaderMetadata responseHeaderMetadata = response.getResponseHeaderMetadata();
                    ResponseMetadata responseMetadata = response.getResponseMetadata();
                    ListOrdersByNextTokenResult listOrdersByNextTokenResult = response.getListOrdersByNextTokenResult();
                    xresponse = response;
                    responseList.add(xresponse);
                    log.info("获取下一页订单成功");
                    break NUM;
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof MarketplaceWebServiceOrdersException) {
                        // Exception properties are important for diagnostics.
                        MarketplaceWebServiceOrdersException ex =
                                (MarketplaceWebServiceOrdersException) cause;
                        ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
                        System.out.println("当前线程：" + Thread.currentThread().getName());
                        System.out.println("Service Exception:");
                        System.out.println("RequestId: " + rhmd.getRequestId());
                        System.out.println("Timestamp: " + rhmd.getTimestamp());
                        System.out.println("Message: " + ex.getMessage());
                        System.out.println("StatusCode: " + ex.getStatusCode());
                        System.out.println("ErrorCode: " + ex.getErrorCode());
                        System.out.println("ErrorType: " + ex.getErrorType());
                        //xresponse = ex;
                        try {
                            if (ex.getStatusCode() == 503) {
                                System.out.println("睡眠1分钟");
                                Thread.sleep(61000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        //xresponse = cause;
                    }
                } catch (Exception e) {
                    //xresponse = e;
                    e.printStackTrace();
                }
            }
        }
        return responseList;
    }


    /**
     * 获取下一页订单数据的递归方法
     */
    private static List<Order> getOrderListByNextToken(List<Order> orderList, MarketplaceWebServiceOrdersAsync client, String sellerId, String mwsAuthToken, String nextToken) {
        //准备接口需要的数据
        List<ListOrdersByNextTokenRequest> listOrdersByNextTokenRequests = new ArrayList<ListOrdersByNextTokenRequest>();
        ListOrdersByNextTokenRequest listOrdersByNextTokenRequest = new ListOrdersByNextTokenRequest();
        listOrdersByNextTokenRequest.setSellerId(sellerId);
        listOrdersByNextTokenRequest.setMWSAuthToken(mwsAuthToken);
        listOrdersByNextTokenRequest.setNextToken(nextToken);
        listOrdersByNextTokenRequests.add(listOrdersByNextTokenRequest);
        List<Object> listOrdersByNextTokenList = invokeListOrdersByNextToken(client, listOrdersByNextTokenRequests);
        ListOrdersByNextTokenResponse listOrdersByNextTokenResponse = (ListOrdersByNextTokenResponse) (listOrdersByNextTokenList.get(0));
        orderList.addAll(listOrdersByNextTokenResponse.getListOrdersByNextTokenResult().getOrders());
        String nextToken1 = listOrdersByNextTokenResponse.getListOrdersByNextTokenResult().getNextToken();
        if (nextToken1 != null) {
            getOrderListByNextToken(orderList, client, sellerId, mwsAuthToken, nextToken1);
        }
        return orderList;
    }

    /**
     * 获取当前订单明细的实现方法
     */
    public static HashMap<String, List<OrderItem>> invokeListOrderItems(MarketplaceWebServiceOrdersAsync client, List<ListOrderItemsRequest> requestList) {
        // Call the service async.
        log.info("获取订单明细开始");
        HashMap<String, List<OrderItem>> orderItemsResultMap = new HashMap<>();
        for (ListOrderItemsRequest request : requestList) {
            String sellerId = request.getSellerId();
            String mwsAuthToken = request.getMWSAuthToken();
            List<OrderItem> newOrderItemList = new ArrayList<>();
            NUM:
            for (int i = 0; i < MAX_ERROR_NUM; i++) {
                try {
                    Future<ListOrderItemsResponse> future = client.listOrderItemsAsync(request);
                    ListOrderItemsResponse response = future.get();
                    ResponseHeaderMetadata responseHeaderMetadata = response.getResponseHeaderMetadata();
                    ResponseMetadata responseMetadata = response.getResponseMetadata();
                    ListOrderItemsResult listOrderItemsResult = response.getListOrderItemsResult();
                    String nextToken = listOrderItemsResult.getNextToken();
                    newOrderItemList.addAll(listOrderItemsResult.getOrderItems());
                    if (nextToken != null) {
                        newOrderItemList = getOrderItemListByNextToken(newOrderItemList, client, sellerId, mwsAuthToken, nextToken);
                    }
                    // We recommend logging every the request id and timestamp of every call.
                    System.out.println("Response:");
                    System.out.println("RequestId: " + responseHeaderMetadata.getRequestId());
                    System.out.println("Timestamp: " + responseHeaderMetadata.getTimestamp());
                    System.out.println("orderId:" + request.getAmazonOrderId());
                    System.out.println("orderItemSize:" + newOrderItemList.size());
                    orderItemsResultMap.put(request.getAmazonOrderId(), newOrderItemList);
                    log.info("获取" + request.getAmazonOrderId() + "的订单明细结束");
                    break NUM;
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof MarketplaceWebServiceOrdersException) {
                        // Exception properties are important for diagnostics.
                        MarketplaceWebServiceOrdersException ex =
                                (MarketplaceWebServiceOrdersException) cause;
                        ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
                        System.out.println("当前线程：" + Thread.currentThread().getName());
                        System.out.println("Service Exception:");
                        System.out.println("RequestId: " + rhmd.getRequestId());
                        System.out.println("Timestamp: " + rhmd.getTimestamp());
                        System.out.println("Message: " + ex.getMessage());
                        System.out.println("StatusCode: " + ex.getStatusCode());
                        System.out.println("ErrorCode: " + ex.getErrorCode());
                        System.out.println("ErrorType: " + ex.getErrorType());
                        try {
                            if (ex.getStatusCode() == 503) {
                                System.out.println("睡眠2.1秒钟");
                                Thread.sleep(2100);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("获取店铺：" + "所有订单明细结束");
        return orderItemsResultMap;
    }

    /**
     * 获取下一页订单明细的实现方法
     */
    private static List<Object> invokeListOrderItemsByNextToken(MarketplaceWebServiceOrdersAsync client, List<ListOrderItemsByNextTokenRequest> requestList) {
        // Call the service async.
        List<Object> responseList = new ArrayList<Object>();
        for (ListOrderItemsByNextTokenRequest request : requestList) {

            NUM:
            for (int i = 0; i < MAX_ERROR_NUM; i++) {
                Object xresponse;
                try {
                    Future<ListOrderItemsByNextTokenResponse> future = client.listOrderItemsByNextTokenAsync(request);
                    ListOrderItemsByNextTokenResponse response = future.get();
                    ResponseHeaderMetadata responseHeaderMetadata = response.getResponseHeaderMetadata();
                    ResponseMetadata responseMetadata = response.getResponseMetadata();
                    ListOrderItemsByNextTokenResult listOrderItemsByNextTokenResult = response.getListOrderItemsByNextTokenResult();
                    // We recommend logging every the request id and timestamp of every call.
                    System.out.println("orderId:" + listOrderItemsByNextTokenResult.getAmazonOrderId());
                    System.out.println("RequestId: " + responseHeaderMetadata.getRequestId());
                    System.out.println("Timestamp: " + responseHeaderMetadata.getTimestamp());
                    String responseXml = response.toXML();
                    System.out.println(responseXml);
                    xresponse = response;
                    responseList.add(xresponse);
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof MarketplaceWebServiceOrdersException) {
                        // Exception properties are important for diagnostics.
                        MarketplaceWebServiceOrdersException ex =
                                (MarketplaceWebServiceOrdersException) cause;
                        ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
                        System.out.println("当前线程：" + Thread.currentThread().getName());
                        System.out.println("Service Exception:");
                        System.out.println("RequestId: " + rhmd.getRequestId());
                        System.out.println("Timestamp: " + rhmd.getTimestamp());
                        System.out.println("Message: " + ex.getMessage());
                        System.out.println("StatusCode: " + ex.getStatusCode());
                        System.out.println("ErrorCode: " + ex.getErrorCode());
                        System.out.println("ErrorType: " + ex.getErrorType());
                        try {
                            if (ex.getStatusCode() == 503) {
                                System.out.println("睡眠2.1秒钟");
                                Thread.sleep(2100);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return responseList;
    }

    /**
     * 获取下一页订单明细数据的递归方法
     */
    private static List<OrderItem> getOrderItemListByNextToken(List<OrderItem> orderItemList, MarketplaceWebServiceOrdersAsync client, String sellerId, String mwsAuthToken, String nextToken) {
        //准备接口需要的数据
        List<ListOrderItemsByNextTokenRequest> listOrderItemsByNextTokenRequests = new ArrayList<ListOrderItemsByNextTokenRequest>();
        ListOrderItemsByNextTokenRequest listOrderItemsByNextTokenRequest = new ListOrderItemsByNextTokenRequest();
        listOrderItemsByNextTokenRequest.setSellerId(sellerId);
        listOrderItemsByNextTokenRequest.setMWSAuthToken(mwsAuthToken);
        listOrderItemsByNextTokenRequest.setNextToken(nextToken);
        listOrderItemsByNextTokenRequests.add(listOrderItemsByNextTokenRequest);
        List<Object> listOrdersByNextTokenList = invokeListOrderItemsByNextToken(client, listOrderItemsByNextTokenRequests);
        ListOrderItemsByNextTokenResponse listOrderItemsByNextTokenResponse = (ListOrderItemsByNextTokenResponse) (listOrdersByNextTokenList.get(0));
        orderItemList.addAll(listOrderItemsByNextTokenResponse.getListOrderItemsByNextTokenResult().getOrderItems());
        String nextToken1 = listOrderItemsByNextTokenResponse.getListOrderItemsByNextTokenResult().getNextToken();
        if (nextToken1 != null) {
            getOrderItemListByNextToken(orderItemList, client, sellerId, mwsAuthToken, nextToken1);
        }
        return orderItemList;
    }


    /**
     * 封装order相关数据
     */
    private HashMap<String, List> packageOrderData(List<Order> orderList, String brandName, String sellerId, String area) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        HashMap<String, List> resultMap = new HashMap<>(5);
        List<MwsOrders> mwsOrdersList = new ArrayList<>();
        List<MwsOrdersBuyerTaxInfo> mwsOrdersBuyerTaxInfoList = new ArrayList<>();
        List<MwsOrdersPaymentExecutionDetail> mwsOrdersPaymentExecutionDetailList = new ArrayList<>();
        List<MwsOrdersPaymentMethodDetails> mwsOrdersPaymentMethodDetailsList = new ArrayList<>();
        List<MwsOrdersTaxRegistrationDetails> mwsOrdersTaxRegistrationDetailsList = new ArrayList<>();
        if (orderList == null || orderList.size() == 0) {
            return resultMap;
        }
        for (Order order : orderList) {
            String amazonOrderId = order.getAmazonOrderId();
            //订单主体部分
            MwsOrders mwsOrders = new MwsOrders();
            mwsOrders.setBrandName(brandName);
            mwsOrders.setSellerId(sellerId);
            mwsOrders.setArea(area);
            mwsOrders.setAmazonOrderId(amazonOrderId);
            if (null != order.getSellerOrderId())
                mwsOrders.setSellerOrderId(order.getSellerOrderId());
            XMLGregorianCalendar orderPurchaseDate = order.getPurchaseDate();
            LocalDateTime purchaseDate = LocalDateTime.of(orderPurchaseDate.getYear(), orderPurchaseDate.getMonth(), orderPurchaseDate.getDay(), orderPurchaseDate.getHour(), orderPurchaseDate.getMinute(), orderPurchaseDate.getSecond());
            mwsOrders.setPurchaseDate(purchaseDate.format(df));
            XMLGregorianCalendar orderLastUpdateDate = order.getLastUpdateDate();
            LocalDateTime lastUpdateDate = LocalDateTime.of(orderLastUpdateDate.getYear(), orderLastUpdateDate.getMonth(), orderLastUpdateDate.getDay(), orderLastUpdateDate.getHour(), orderLastUpdateDate.getMinute(), orderLastUpdateDate.getSecond());
            mwsOrders.setLastUpdateDate(lastUpdateDate.format(df));
            mwsOrders.setOrderStatus(order.getOrderStatus());
            if (null != order.getFulfillmentChannel())
                mwsOrders.setFulfillmentChannel(order.getFulfillmentChannel());
            if (null != order.getSalesChannel())
                mwsOrders.setSalesChannel(order.getSalesChannel());
            if (null != order.getOrderChannel())
                mwsOrders.setOrderChannel(order.getOrderChannel());
            if (null != order.getShipServiceLevel())
                mwsOrders.setShipServiceLevel(order.getShipServiceLevel());
            if (null != order.getShippingAddress()) {
                Address address = order.getShippingAddress();
                if (null != address.getAddressLine1())
                    mwsOrders.setShippingAddressAddressline1(address.getAddressLine1());
                if (null != address.getAddressLine2())
                    mwsOrders.setShippingAddressAddressline2(address.getAddressLine2());
                if (null != address.getAddressLine3())
                    mwsOrders.setShippingAddressAddressline3(address.getAddressLine3());
                if (null != address.getCity())
                    mwsOrders.setShippingAddressCity(address.getCity());
                if (null != address.getCounty())
                    mwsOrders.setShippingAddressCounty(address.getCounty());
                if (null != address.getDistrict())
                    mwsOrders.setShippingAddressDistrict(address.getDistrict());
                if (null != address.getStateOrRegion())
                    mwsOrders.setShippingAddressStateOrRegion(address.getStateOrRegion());
                if (null != address.getMunicipality())
                    mwsOrders.setShippingAddressMunicipality(address.getMunicipality());
                if (null != address.getPostalCode())
                    mwsOrders.setShippingAddressPostalCode(address.getPostalCode());
                if (null != address.getCountryCode())
                    mwsOrders.setShippingAddressCountryCode(address.getCountryCode());
                if (null != address.getPhone())
                    mwsOrders.setShippingAddressPhone(address.getPhone());
                if (null != address.getAddressType())
                    mwsOrders.setShippingAddressAddressType(address.getAddressType());
                if (null != address.getIsAddressSharingConfidential())
                    mwsOrders.setShippingAddressIsAddressSharingConfidential(address.getIsAddressSharingConfidential());
            }
            if (null != order.getOrderTotal()) {
                Money orderTotal = order.getOrderTotal();
                if (null != orderTotal.getCurrencyCode())
                    mwsOrders.setOrderTotalCurrencyCode(orderTotal.getCurrencyCode());
                if (null != orderTotal.getAmount())
                    mwsOrders.setOrderTotalAmount(BigDecimal.valueOf(Double.parseDouble(orderTotal.getAmount())));
            }
            if (null != order.getNumberOfItemsShipped())
                mwsOrders.setNumberOfItemsShipped(order.getNumberOfItemsShipped());
            if (null != order.getNumberOfItemsUnshipped())
                mwsOrders.setNumberOfItemsUnshipped(order.getNumberOfItemsUnshipped());
            if (null != order.getPaymentMethod())
                mwsOrders.setPaymentMethod(order.getPaymentMethod());
            if (null != order.getMarketplaceId())
                mwsOrders.setMarketplaceId(order.getMarketplaceId());
            if (null != order.getBuyerEmail())
                mwsOrders.setBuyerEmail(order.getBuyerEmail());
            if (null != order.getBuyerName())
                mwsOrders.setBuyerName(order.getBuyerName());
            if (null != order.getBuyerCounty())
                mwsOrders.setBuyerCounty(order.getBuyerCounty());
            if (null != order.getShipmentServiceLevelCategory())
                mwsOrders.setShipmentServiceLevelCategory(order.getShipmentServiceLevelCategory());
            if (null != order.getShippedByAmazonTFM())
                mwsOrders.setShippedByAmazonTfm(order.getShippedByAmazonTFM());
            if (null != order.getTFMShipmentStatus())
                mwsOrders.setTfmShipmentStatus(order.getTFMShipmentStatus());
            if (null != order.getEasyShipShipmentStatus())
                mwsOrders.setEasyShipShipmentStatus(order.getEasyShipShipmentStatus());
            if (null != order.getCbaDisplayableShippingLabel())
                mwsOrders.setCbaDisplayableShippingLabel(order.getCbaDisplayableShippingLabel());
            if (null != order.getOrderType())
                mwsOrders.setOrderType(order.getOrderType());
            if (null != order.getEarliestShipDate()) {
                XMLGregorianCalendar orderEarliestShipDate = order.getEarliestShipDate();
                LocalDateTime earliestShipDate = LocalDateTime.of(orderEarliestShipDate.getYear(), orderEarliestShipDate.getMonth(), orderEarliestShipDate.getDay(), orderEarliestShipDate.getHour(), orderEarliestShipDate.getMinute(), orderEarliestShipDate.getSecond());
                mwsOrders.setEarliestShipDate(earliestShipDate.format(df));
            }
            if (null != order.getLatestShipDate()) {
                XMLGregorianCalendar orderLatestShipDate = order.getLatestShipDate();
                LocalDateTime latestShipDate = LocalDateTime.of(orderLatestShipDate.getYear(), orderLatestShipDate.getMonth(), orderLatestShipDate.getDay(), orderLatestShipDate.getHour(), orderLatestShipDate.getMinute(), orderLatestShipDate.getSecond());
                mwsOrders.setLatestShipDate(latestShipDate.format(df));
            }
            if (null != order.getIsBusinessOrder())
                mwsOrders.setIsBusinessOrder(order.getIsBusinessOrder());
            if (null != order.getPurchaseOrderNumber())
                mwsOrders.setPurchaseOrderNumber(order.getPurchaseOrderNumber());
            if (null != order.getIsPrime())
                mwsOrders.setIsPrime(order.getIsPrime());
            if (null != order.getIsGlobalExpressEnabled())
                mwsOrders.setIsGlobalExpressEnabled(order.getIsGlobalExpressEnabled());
            if (null != order.getIsPremiumOrder())
                mwsOrders.setIsPremiumOrder(order.getIsPremiumOrder());
            if (null != order.getReplacedOrderId())
                mwsOrders.setReplacedOrderId(order.getReplacedOrderId());
            if (null != order.getIsReplacementOrder())
                mwsOrders.setIsReplacementOrder(order.getIsReplacementOrder());
            if (null != order.getPromiseResponseDueDate()) {
                XMLGregorianCalendar orderPromiseResponseDueDate = order.getPromiseResponseDueDate();
                LocalDateTime promiseResponseDueDate = LocalDateTime.of(orderPromiseResponseDueDate.getYear(), orderPromiseResponseDueDate.getMonth(), orderPromiseResponseDueDate.getDay(), orderPromiseResponseDueDate.getHour(), orderPromiseResponseDueDate.getMinute(), orderPromiseResponseDueDate.getSecond());
                mwsOrders.setPromiseResponseDueDate(promiseResponseDueDate.format(df));
            }
            if (null != order.getIsEstimatedShipDateSet())
                mwsOrders.setIsEstimatedShipDateSet(order.getIsEstimatedShipDateSet());
            if (null != order.getIsSoldByAB())
                mwsOrders.setIsSoldByAb(order.getIsSoldByAB());
            mwsOrdersList.add(mwsOrders);
            //有关买方的税收信息
            if (null != order.getBuyerTaxInfo()) {
                BuyerTaxInfo buyerTaxInfo = order.getBuyerTaxInfo();
                if (null != buyerTaxInfo.getTaxClassifications()) {
                    List<TaxClassification> taxClassifications = buyerTaxInfo.getTaxClassifications();
                    for (TaxClassification taxClassification : taxClassifications) {
                        MwsOrdersBuyerTaxInfo mwsOrdersBuyerTaxInfo = new MwsOrdersBuyerTaxInfo();
                        mwsOrdersBuyerTaxInfo.setAmazonOrderId(amazonOrderId);
                        if (null != buyerTaxInfo.getCompanyLegalName())
                            mwsOrdersBuyerTaxInfo.setCompanyLegalName(buyerTaxInfo.getCompanyLegalName());
                        if (null != buyerTaxInfo.getTaxingRegion())
                            mwsOrdersBuyerTaxInfo.setTaxingRegion(buyerTaxInfo.getTaxingRegion());
                        if (null != taxClassification.getName())
                            mwsOrdersBuyerTaxInfo.setTaxClassificationName(taxClassification.getName());
                        if (null != taxClassification.getValue())
                            mwsOrdersBuyerTaxInfo.setTaxClassificationValue(taxClassification.getValue());
                        mwsOrdersBuyerTaxInfoList.add(mwsOrdersBuyerTaxInfo);
                    }
                } else {
                    MwsOrdersBuyerTaxInfo mwsOrdersBuyerTaxInfo = new MwsOrdersBuyerTaxInfo();
                    mwsOrdersBuyerTaxInfo.setAmazonOrderId(amazonOrderId);
                    if (null != buyerTaxInfo.getCompanyLegalName())
                        mwsOrdersBuyerTaxInfo.setCompanyLegalName(buyerTaxInfo.getCompanyLegalName());
                    if (null != buyerTaxInfo.getTaxingRegion())
                        mwsOrdersBuyerTaxInfo.setTaxingRegion(buyerTaxInfo.getTaxingRegion());
                    mwsOrdersBuyerTaxInfoList.add(mwsOrdersBuyerTaxInfo);
                }

            }

            //有关货到付款（COD）订单的子付款方式的信息
            if (null != order.getPaymentExecutionDetail()) {
                List<PaymentExecutionDetailItem> paymentExecutionDetail = order.getPaymentExecutionDetail();
                for (PaymentExecutionDetailItem paymentExecutionDetailItem : paymentExecutionDetail) {
                    MwsOrdersPaymentExecutionDetail mwsOrdersPaymentExecutionDetail = new MwsOrdersPaymentExecutionDetail();
                    mwsOrdersPaymentExecutionDetail.setAmazonOrderId(amazonOrderId);
                    if (null != paymentExecutionDetailItem.getPayment()) {
                        Money payment = paymentExecutionDetailItem.getPayment();
                        if (null != payment.getCurrencyCode())
                            mwsOrdersPaymentExecutionDetail.setPaymentCurrencyCode(payment.getCurrencyCode());
                        if (null != payment.getCurrencyCode())
                            mwsOrdersPaymentExecutionDetail.setPaymentAmount(BigDecimal.valueOf(Double.parseDouble(payment.getAmount())));
                    }
                    if (null != paymentExecutionDetailItem.getPaymentMethod())
                        mwsOrdersPaymentExecutionDetail.setPaymentMethod(paymentExecutionDetailItem.getPaymentMethod());
                    mwsOrdersPaymentExecutionDetailList.add(mwsOrdersPaymentExecutionDetail);
                }
            }
            //订单的付款方式列表
            if (null != order.getPaymentMethodDetails()) {
                List<String> paymentMethodDetails = order.getPaymentMethodDetails();
                for (String paymentMethodDetail : paymentMethodDetails) {
                    MwsOrdersPaymentMethodDetails mwsOrdersPaymentMethodDetails = new MwsOrdersPaymentMethodDetails();
                    mwsOrdersPaymentMethodDetails.setAmazonOrderId(amazonOrderId);
                    mwsOrdersPaymentMethodDetails.setPaymentMethodDetail(paymentMethodDetail);
                    mwsOrdersPaymentMethodDetailsList.add(mwsOrdersPaymentMethodDetails);
                }
            }
            //订单税务登记详细信息
            if (null != order.getTaxRegistrationDetails()) {
                List<TaxRegistrationDetails> taxRegistrationDetails = order.getTaxRegistrationDetails();
                for (TaxRegistrationDetails taxRegistrationDetail : taxRegistrationDetails) {
                    MwsOrdersTaxRegistrationDetails mwsOrdersTaxRegistrationDetails = new MwsOrdersTaxRegistrationDetails();
                    mwsOrdersTaxRegistrationDetails.setAmazonOrderId(amazonOrderId);
                    if (null != taxRegistrationDetail.getTaxRegistrationType())
                        mwsOrdersTaxRegistrationDetails.setTaxRegistrationType(taxRegistrationDetail.getTaxRegistrationType());
                    if (null != taxRegistrationDetail.getTaxRegistrationId())
                        mwsOrdersTaxRegistrationDetails.setTaxRegistrationId(taxRegistrationDetail.getTaxRegistrationId());
                    if (null != taxRegistrationDetail.getTaxRegistrationAuthority()) {
                        TaxRegistrationAuthority taxRegistrationAuthority = taxRegistrationDetail.getTaxRegistrationAuthority();
                        if (null != taxRegistrationAuthority.getCountry())
                            mwsOrdersTaxRegistrationDetails.setTaxRegistrationAuthorityCountry(taxRegistrationAuthority.getCountry());
                        if (null != taxRegistrationAuthority.getState())
                            mwsOrdersTaxRegistrationDetails.setTaxRegistrationAuthorityState(taxRegistrationAuthority.getState());
                        if (null != taxRegistrationAuthority.getDistrict())
                            mwsOrdersTaxRegistrationDetails.setTaxRegistrationAuthorityDistrict(taxRegistrationAuthority.getDistrict());
                        if (null != taxRegistrationAuthority.getProvince())
                            mwsOrdersTaxRegistrationDetails.setTaxRegistrationAuthorityProvince(taxRegistrationAuthority.getProvince());
                        if (null != taxRegistrationAuthority.getCity())
                            mwsOrdersTaxRegistrationDetails.setTaxRegistrationAuthorityCity(taxRegistrationAuthority.getCity());
                        if (null != taxRegistrationAuthority.getWarehouseId())
                            mwsOrdersTaxRegistrationDetails.setTaxRegistrationAuthorityWarehouseId(taxRegistrationAuthority.getWarehouseId());
                    }
                    mwsOrdersTaxRegistrationDetailsList.add(mwsOrdersTaxRegistrationDetails);
                }
            }
        }
        resultMap.put("mwsOrdersList", mwsOrdersList);
        resultMap.put("mwsOrdersBuyerTaxInfoList", mwsOrdersBuyerTaxInfoList);
        resultMap.put("mwsOrdersPaymentExecutionDetailList", mwsOrdersPaymentExecutionDetailList);
        resultMap.put("mwsOrdersPaymentMethodDetailsList", mwsOrdersPaymentMethodDetailsList);
        resultMap.put("mwsOrdersTaxRegistrationDetailsList", mwsOrdersTaxRegistrationDetailsList);
        return resultMap;
    }

    /**
     * 封装订单明细数据
     */
    private HashMap<String, List> packageOrderItemData(HashMap<String, List<OrderItem>> listOrderItemsMap) {
        HashMap<String, List> resultMap = new HashMap<>(2);
        List<MwsOrderItems> mwsOrderItemsList = new ArrayList<>();
        List<MwsOrderItemsPromotionIds> mwsOrderItemsPromotionIdsList = new ArrayList<>();
        if (listOrderItemsMap.entrySet().size() == 0) {
            return resultMap;
        }
        Set<Map.Entry<String, List<OrderItem>>> entrySet = listOrderItemsMap.entrySet();
        for (Map.Entry<String, List<OrderItem>> entry : entrySet) {
            String amazonOrderId = entry.getKey();
            List<OrderItem> orderItemList = entry.getValue();
            for (OrderItem orderItem : orderItemList) {
                //订单明细主体
                MwsOrderItems mwsOrderItems = new MwsOrderItems();
                String orderItemId = orderItem.getOrderItemId();
                mwsOrderItems.setAmazonOrderId(amazonOrderId);
                mwsOrderItems.setAsin(orderItem.getASIN());
                if (null != orderItem.getSellerSKU())
                    mwsOrderItems.setSellerSku(orderItem.getSellerSKU());
                mwsOrderItems.setOrderItemId(orderItemId);
                if (null != orderItem.getTitle())
                    mwsOrderItems.setTitle(orderItem.getTitle());
                mwsOrderItems.setQuantityOrdered(orderItem.getQuantityOrdered());
                if (null != orderItem.getQuantityShipped())
                    mwsOrderItems.setQuantityShipped(orderItem.getQuantityShipped());
                if (null != orderItem.getProductInfo()) {
                    ProductInfoDetail productInfo = orderItem.getProductInfo();
                    if (null != productInfo.getNumberOfItems())
                        mwsOrderItems.setProductInfoNumberOfItems(productInfo.getNumberOfItems());
                }
                if (null != orderItem.getPointsGranted()) {
                    PointsGrantedDetail pointsGranted = orderItem.getPointsGranted();
                    mwsOrderItems.setPointsGrantedPointsNumber(pointsGranted.getPointsNumber());
                    if (null != pointsGranted.getPointsMonetaryValue()) {
                        Money pointsMonetaryValue = pointsGranted.getPointsMonetaryValue();
                        if (null != pointsMonetaryValue.getCurrencyCode())
                            mwsOrderItems.setPointsGrantedPointsMonetaryValueCurrencyCode(pointsMonetaryValue.getCurrencyCode());
                        if (null != pointsMonetaryValue.getAmount())
                            mwsOrderItems.setPointsGrantedPointsMonetaryValueAmount(BigDecimal.valueOf(Double.parseDouble(pointsMonetaryValue.getAmount())));
                    }
                }
                if (null != orderItem.getItemPrice()) {
                    Money itemPrice = orderItem.getItemPrice();
                    if (null != itemPrice.getCurrencyCode())
                        mwsOrderItems.setItemPriceCurrencyCode(itemPrice.getCurrencyCode());
                    if (null != itemPrice.getAmount())
                        mwsOrderItems.setItemPriceAmount(BigDecimal.valueOf(Double.parseDouble(itemPrice.getAmount())));
                }
                if (null != orderItem.getShippingPrice()) {
                    Money shippingPrice = orderItem.getShippingPrice();
                    if (null != shippingPrice.getCurrencyCode())
                        mwsOrderItems.setShippingPriceCurrencyCode(shippingPrice.getCurrencyCode());
                    if (null != shippingPrice.getAmount())
                        mwsOrderItems.setShippingPriceAmount(BigDecimal.valueOf(Double.parseDouble(shippingPrice.getAmount())));
                }
                if (null != orderItem.getGiftWrapTax()) {
                    Money giftWrapTax = orderItem.getGiftWrapTax();
                    if (null != giftWrapTax.getCurrencyCode())
                        mwsOrderItems.setGiftWrapTaxCurrencyCode(giftWrapTax.getCurrencyCode());
                    if (null != giftWrapTax.getAmount())
                        mwsOrderItems.setGiftWrapTaxAmount(BigDecimal.valueOf(Double.parseDouble(giftWrapTax.getAmount())));
                }
                if (null != orderItem.getShippingDiscount()) {
                    Money shippingDiscount = orderItem.getShippingDiscount();
                    if (null != shippingDiscount.getCurrencyCode())
                        mwsOrderItems.setShippingDiscountCurrencyCode(shippingDiscount.getCurrencyCode());
                    if (null != shippingDiscount.getAmount())
                        mwsOrderItems.setShippingDiscountAmount(BigDecimal.valueOf(Double.parseDouble(shippingDiscount.getAmount())));
                }
                if (null != orderItem.getShippingDiscountTax()) {
                    Money shippingDiscountTax = orderItem.getShippingDiscountTax();
                    if (null != shippingDiscountTax.getCurrencyCode())
                        mwsOrderItems.setShippingDiscountTaxCurrencyCode(shippingDiscountTax.getCurrencyCode());
                    if (null != shippingDiscountTax.getAmount())
                        mwsOrderItems.setShippingDiscountTaxAmount(BigDecimal.valueOf(Double.parseDouble(shippingDiscountTax.getAmount())));
                }
                if (null != orderItem.getPromotionDiscount()) {
                    Money promotionDiscount = orderItem.getPromotionDiscount();
                    if (null != promotionDiscount.getCurrencyCode())
                        mwsOrderItems.setPromotionDiscountCurrencyCode(promotionDiscount.getCurrencyCode());
                    if (null != promotionDiscount.getAmount())
                        mwsOrderItems.setPromotionDiscountAmount(BigDecimal.valueOf(Double.parseDouble(promotionDiscount.getAmount())));
                }
                if (null != orderItem.getPromotionDiscountTax()) {
                    Money promotionDiscountTax = orderItem.getPromotionDiscountTax();
                    if (null != promotionDiscountTax.getCurrencyCode())
                        mwsOrderItems.setPromotionDiscountTaxCurrencyCode(promotionDiscountTax.getCurrencyCode());
                    if (null != promotionDiscountTax.getAmount())
                        mwsOrderItems.setPromotionDiscountTaxAmount(BigDecimal.valueOf(Double.parseDouble(promotionDiscountTax.getAmount())));
                }
                if (null != orderItem.getCODFee()) {
                    Money codFee = orderItem.getCODFee();
                    if (null != codFee.getCurrencyCode())
                        mwsOrderItems.setCodFeeCurrencyCode(codFee.getCurrencyCode());
                    if (null != codFee.getAmount())
                        mwsOrderItems.setCodFeeAmount(BigDecimal.valueOf(Double.parseDouble(codFee.getAmount())));
                }
                if (null != orderItem.getCODFeeDiscount()) {
                    Money codFeeDiscount = orderItem.getCODFeeDiscount();
                    if (null != codFeeDiscount.getCurrencyCode())
                        mwsOrderItems.setCodFeeDiscountCurrencyCode(codFeeDiscount.getCurrencyCode());
                    if (null != codFeeDiscount.getAmount())
                        mwsOrderItems.setCodFeeDiscountAmount(BigDecimal.valueOf(Double.parseDouble(codFeeDiscount.getAmount())));
                }
                if (null != orderItem.getIsGift())
                    mwsOrderItems.setIsGift(orderItem.getIsGift());
                if (null != orderItem.getGiftMessageText())
                    mwsOrderItems.setGiftMessageText(orderItem.getGiftMessageText());
                if (null != orderItem.getGiftWrapLevel())
                    mwsOrderItems.setGiftWrapLevel(orderItem.getGiftWrapLevel());
                if (null != orderItem.getInvoiceData()) {
                    InvoiceData invoiceData = orderItem.getInvoiceData();
                    if (null != invoiceData.getInvoiceRequirement())
                        mwsOrderItems.setInvoiceDataInvoiceRequirement(invoiceData.getInvoiceRequirement());
                    if (null != invoiceData.getBuyerSelectedInvoiceCategory())
                        mwsOrderItems.setInvoiceDataBuyerSelectedInvoiceCategory(invoiceData.getBuyerSelectedInvoiceCategory());
                    if (null != invoiceData.getInvoiceTitle())
                        mwsOrderItems.setInvoiceDataInvoiceTitle(invoiceData.getInvoiceTitle());
                    if (null != invoiceData.getInvoiceInformation())
                        mwsOrderItems.setInvoiceDataInvoiceInformation(invoiceData.getInvoiceInformation());
                }
                if (null != orderItem.getConditionNote())
                    mwsOrderItems.setConditionNote(orderItem.getConditionNote());
                if (null != orderItem.getConditionId())
                    mwsOrderItems.setConditionId(orderItem.getConditionId());
                if (null != orderItem.getConditionSubtypeId())
                    mwsOrderItems.setConditionSubtypeId(orderItem.getConditionSubtypeId());
                if (null != orderItem.getScheduledDeliveryStartDate())
                    mwsOrderItems.setScheduledDeliveryStartDate(orderItem.getScheduledDeliveryStartDate());
                if (null != orderItem.getScheduledDeliveryEndDate())
                    mwsOrderItems.setScheduledDeliveryEndDate(orderItem.getScheduledDeliveryEndDate());
                if (null != orderItem.getPriceDesignation())
                    mwsOrderItems.setPriceDesignation(orderItem.getPriceDesignation());
                if (null != orderItem.getBuyerCustomizedInfo()) {
                    BuyerCustomizedInfoDetail buyerCustomizedInfo = orderItem.getBuyerCustomizedInfo();
                    if (null != buyerCustomizedInfo.getCustomizedURL())
                        mwsOrderItems.setBuyerCustomizedInfoCustomizedUrl(buyerCustomizedInfo.getCustomizedURL());
                }
                if (null != orderItem.getTaxCollection()) {
                    TaxCollection taxCollection = orderItem.getTaxCollection();
                    if (null != taxCollection.getModel())
                        mwsOrderItems.setTaxCollectionModel(taxCollection.getModel());
                    if (null != taxCollection.getResponsibleParty())
                        mwsOrderItems.setTaxCollectionResponsibleParty(taxCollection.getResponsibleParty());
                }
                if (null != orderItem.getSerialNumberRequired())
                    mwsOrderItems.setSerialNumberRequired(orderItem.getSerialNumberRequired());
                if (null != orderItem.getIsTransparency())
                    mwsOrderItems.setIsTransparency(orderItem.getIsTransparency());
                mwsOrderItemsList.add(mwsOrderItems);
                //mws_order_items_promotion_ids部分
                if (null != orderItem.getPromotionIds()) {
                    List<String> promotionIds = orderItem.getPromotionIds();
                    for (String promotionId : promotionIds) {
                        MwsOrderItemsPromotionIds mwsOrderItemsPromotionIds = new MwsOrderItemsPromotionIds();
                        mwsOrderItemsPromotionIds.setOrderItemId(orderItemId);
                        if (null != promotionId)
                            mwsOrderItemsPromotionIds.setPromotionId(promotionId);
                        mwsOrderItemsPromotionIdsList.add(mwsOrderItemsPromotionIds);
                    }
                }
            }
        }
        resultMap.put("mwsOrderItemsList", mwsOrderItemsList);
        resultMap.put("mwsOrderItemsPromotionIdsList", mwsOrderItemsPromotionIdsList);
        return resultMap;
    }

}
